package leetcode.剑指offer.前40;

import com.google.gson.Gson;
import org.junit.Test;

import java.util.ArrayList;

/**
 * @author :songyaozhang
 * @date :Created 2021/7/28 19:57
 * @description :https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
 */
public class 剑指_29_顺时针打印矩阵 {
    @Test
    public void test() {
        Solution solution = new Solution();
    }

    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            int[] ans = new int[0];
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans;
            int rows = matrix.length;
            int cols = matrix[0].length;
            int totals = rows * cols;
            ans = new int[totals];
            int row = 0, col = 0, index = 0;
            boolean[][] isVisited = new boolean[rows][cols];
            int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
            int dirIndex = 0;
            for (int i = 0; i < totals; i++) {
                ans[index++] = matrix[row][col];
                isVisited[row][col] = true;
                int newRow = row + dirs[dirIndex][0];
                int newCol = col + dirs[dirIndex][1];
                if (newRow < 0 || newRow >= rows
                        || newCol < 0 || newCol >= cols
                        || isVisited[newRow][newCol]) {
                    dirIndex = (dirIndex + 1) % 4;
                }
                row += dirs[dirIndex][0];;
                col += dirs[dirIndex][1];
            }
            return ans;
        }
    }





























}
